<?php
//$redis = new Redis();
//$redis->connect("localhost", 6379);

if(!$this->r->exists(":compl"))
{
	echo 'Loading entries in the Redis DB'.PHP_EOL;
	$file = file('female-names.txt');
	foreach($file as &$line)
	{
		$line = trim($line);
		for($i=0 ; $i < strlen($line); $i++)
		{
			$prefix = substr($line, 0, $i);
			$this->r->zAdd(':compl', 0,$prefix);
		}
		$this->r->zAdd(':compl', 0, $line.'*');
	}
}
else
{
	echo 'NOT loading entries, there is already a \'compl\' key '.PHP_EOL;
}

function autocomplete($prefix, $count)
{
	$results = array();
	$rangeLen = 50;
	$start = $this->r->zRank(':compl', $prefix);
	if(!$start)
	{
		return $results;
	}

	while(count($results) != $count)
	{
		$range = $this->r->zRange(':compl', $start, $start+$rangeLen-1);
		$start += $rangeLen;
		if(!$range OR count($range) == 0)
		{
			break;
		}
		foreach($range as &$entry)
		{
			$minLen = min(strlen($entry), strlen($prefix));
			if(substr($entry, 0, $minLen) !=  substr($prefix, 0, $minLen))
			{
				$count = count($results);
			}
			if(substr($entry, -1) == "*" AND count($results) != $count)
			{
				$results[] = substr($entry, 0, -1);
			}
		}
	}
	return $results;
}

$results = autocomplete('marcell', 50);
foreach($results as &$res)
{
	echo $res.PHP_EOL;
}